package com.aidansmeaton.weightmanager.adapter;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.CursorAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.aidansmeaton.weightmanager.PictureViewerActivity;
import com.aidansmeaton.weightmanager.R;
import com.aidansmeaton.weightmanager.data.DatabaseHelper;
import com.aidansmeaton.weightmanager.util.CalorieHelper;
import com.aidansmeaton.weightmanager.util.ImageHelper;

public class DiaryFoodAdapter extends CursorAdapter {
		
		private LayoutInflater inflater;
		private DatabaseHelper db;
		
		public DiaryFoodAdapter(Context context, Cursor cursor) {
			super(context, cursor);
			
			inflater = LayoutInflater.from(context);
			db = DatabaseHelper.getInstance(context);
		}

		@Override
		public void bindView(View view, final Context context, Cursor cursor) {
						
			// Set tag
			view.setTag(R.id.food_row, cursor.getInt(DatabaseHelper.FOOD_LOG_ID));
			
			// Identify textviews
			Gallery gallery = (Gallery) view.findViewById(R.id.gallery);
			TextView nameText = (TextView) view.findViewById(R.id.food_name);
			TextView suggestionText = (TextView) view.findViewById(R.id.food_name_suggestion);
			TextView caloriesText = (TextView) view.findViewById(R.id.food_calories);
			ImageView purpleBanner = (ImageView) view.findViewById(R.id.purpleBanner);
			ImageView photo = (ImageView) view.findViewById(R.id.photo);
			
			// Get cursor values
			int id = cursor.getInt(DatabaseHelper.FOOD_LOG_ID);
			//int meal = cursor.getInt(DatabaseHelper.FOOD_LOG_MEAL);
			String name = cursor.getString(DatabaseHelper.FOOD_LOG_NAME);
			//String measurement = cursor.getString(DatabaseHelper.FOOD_LOG_MEASUREMENT);
			//int quantity = cursor.getInt(DatabaseHelper.FOOD_LOG_QUANTITY);
			String note = cursor.getString(DatabaseHelper.FOOD_LOG_NOTE);
			//String photo = cursor.getString(DatabaseHelper.FOOD_LOG_PHOTO);
			
			boolean containsUnknown = false;
			int totalCalories = 0;
			Cursor plateCursor = db.getPlateLogs(id);
			plateCursor.moveToFirst();
			while (!plateCursor.isAfterLast()){
				totalCalories += plateCursor.getInt(DatabaseHelper.PLATE_LOG_CALORIES);
				if (plateCursor.getInt(DatabaseHelper.PLATE_LOG_CALORIES) == 0){
					totalCalories += CalorieHelper.getCaloriesFromGrade(plateCursor.getInt(DatabaseHelper.PLATE_LOG_GRADE));
				}
				if (plateCursor.getInt(DatabaseHelper.PLATE_LOG_GRADE) == ImageHelper.PURPLE) containsUnknown = true;
				plateCursor.moveToNext();
			}
			
			// Fill view with values from db
			if (name != null && name.length() > 0){
				nameText.setVisibility(View.VISIBLE);
				nameText.setText(name);
			} else {
				nameText.setVisibility(View.GONE);
			}
			if (note != null && note.length() > 0){
				suggestionText.setVisibility(View.VISIBLE);
				suggestionText.setText(note);
			} else {
				suggestionText.setVisibility(View.GONE);
			}
			caloriesText.setText(""+totalCalories);
			if (!containsUnknown) purpleBanner.setVisibility(View.INVISIBLE);
			
			// Photo
			if (cursor.getString(DatabaseHelper.FOOD_LOG_PHOTO) != null) {
				String fname = context.getFilesDir().getAbsolutePath()+"/"+cursor.getString(DatabaseHelper.FOOD_LOG_PHOTO);
	    		Log.w("",fname);
	    		photo.setImageBitmap(BitmapFactory.decodeFile(fname));
	    		photo.setTag(cursor.getString(DatabaseHelper.FOOD_LOG_PHOTO));
	    		photo.setOnClickListener(new OnClickListener(){
					@Override
					public void onClick(View v) {
						String path = (String) v.getTag();
						//final Uri uri = Uri.parse("file:///data/data/com.aidansmeaton.weightmanager/files/"+path);
						Intent intent = new Intent(v.getContext(), PictureViewerActivity.class);
						intent.putExtra("Path", path);
				    	v.getContext().startActivity(intent);
					}
	    		});
			}
			
			// Add images of each of the plates/ingredients to the gallery
			gallery.setAdapter(new ImageAdapter(context, db.getPlateLogs(id)));
		    
			// For each plate/ingredient in the gallery, add an on click listener
			gallery.setOnItemClickListener(new OnItemClickListener() {
		        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
		        	String message = "";
		        	int plate_id = (Integer) v.getTag(R.id.food_row);
		            Cursor c = db.getPlateLog(plate_id);
		            c.moveToFirst();
		            if (!c.isAfterLast()){
		            	message += c.getString(DatabaseHelper.PLATE_LOG_NOTE);
		            	if (message.length() > 0) message += " - ";
		            	int calories = c.getInt(DatabaseHelper.PLATE_LOG_CALORIES);
		            	if (c.getInt(DatabaseHelper.PLATE_LOG_GRADE) == ImageHelper.PURPLE) message += "Unknown ";
		            	else if (calories==0) message += CalorieHelper.getCaloriesFromGrade(c.getInt(DatabaseHelper.PLATE_LOG_GRADE)) + " ";
		            	else message += calories + " ";
		            	message += context.getString(R.string.calories);
		            }
		            Toast.makeText(parent.getContext(), message, Toast.LENGTH_SHORT).show();
		            c.close();
		        }
		    });
			
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			return inflater.inflate(R.layout.diary_food_row_record, null);
		}
		
		/**
		 * @author Aidan
		 * 
		 * Inner Adapter for Gallery of 'plates' in each list row
		 *
		 */
		private class ImageAdapter extends BaseAdapter {
		    
		    private Context mContext;
		    private List<Integer> plateIDs;	// corresponds to db
		    private List<Integer> plateGrades;

		    public ImageAdapter(Context c, Cursor cursor) {
		        mContext = c;
		        plateIDs = new ArrayList<Integer>();
		        plateGrades = new ArrayList<Integer>();
		        cursor.moveToFirst();
		        while (!cursor.isAfterLast()){
		        	plateGrades.add(cursor.getInt(DatabaseHelper.PLATE_LOG_GRADE));
		        	plateIDs.add(cursor.getInt(DatabaseHelper.PLATE_LOG_ID));
		        	cursor.moveToNext();
		        }
		    }

		    public int getCount() {
		        return plateIDs.size();
		    }

		    public Object getItem(int position) {
		        return position;
		    }

		    public long getItemId(int position) {
		        return position;
		    }

		    public View getView(int position, View convertView, ViewGroup parent) {
		        ImageView imageView = new ImageView(mContext);

		        imageView.setTag(R.id.food_row, plateIDs.get(position));
		        imageView.setImageResource(ImageHelper.getPlate(plateGrades.get(position)));
		        imageView.setLayoutParams(new Gallery.LayoutParams(100, 75));
		        imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);

		        return imageView;
		    }
		    
		}
		
	}